import { createAxios } from '@/utils/http/axios';
import { getToken } from '@/utils/auth';

enum Api {
  listHistoryLog = '/tbuser/iotDeviceLogSequence/selectList',
  exportHistoryLog = '/tbuser/iotDeviceLogSequence/export',
}

export function exportHistoryLogApi(data: {
  sn: string;
  startTs: number;
  endTs: number;
  fileType: 'xlsx';
}) {
  const token = getToken();
  fetch('/hc-api' + Api.exportHistoryLog, {
    method: 'POST',
    body: JSON.stringify({
      sn: data.sn,
      beginTime: data.startTs, //开始时间
      endTime: data.endTs, //结束时间
      fileType: data.fileType,
    }),
    headers: [
      ['ContentType', 'application/json;charset=UTF-8'],
      ['Authorization', token],
    ],
  })
    .then(function (response: Response) {
      return response.blob();
    })
    .then(function (blob) {
      const link = document.createElement('a');
      link.style.display = 'none';
      link.href = URL.createObjectURL(blob);
      document.body.appendChild(link);
      link.click();
      // 释放的 URL 对象以及移除 a 标签
      URL.revokeObjectURL(link.href);
      document.body.removeChild(link);
    });
}

export function listHistoryLogApi(data: { sn: string; startTs: number; endTs: number }) {
  return createAxios({
    requestOptions: {
      apiUrl: '/hc-api',
    },
  }).post(
    {
      url: Api.listHistoryLog,
      data: {
        sn: data.sn,
        beginTime: data.startTs, //开始时间
        endTime: data.endTs, //结束时间
      },
    },
    {
      retryRequest: {
        isOpenRetry: true,
        count: 5,
        waitTime: 1000,
      },
    },
  );
}
